package com.ruoyi.common;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Dict;
import com.ruoyi.common.api.ICommonAPI;
import com.ruoyi.common.constant.DictConstants;
import com.ruoyi.common.utils.oConvertUtils;
import com.ruoyi.common.vo.DictModel;
import com.ruoyi.system.service.ISysDictDataService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 底层共通业务API，提供其他独立模块调用
 * @Author: scott
 * @Date:2019-4-20 
 * @Version:V1.0
 */
@Service
public class CommonApiImpl implements ICommonAPI {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource
	public ISysDictDataService dictDataService;

	@Override
	public List convertDict(List list) {
		List<JSONObject> items = new ArrayList<>();
		for (Object record : list) {
			ObjectMapper mapper = new ObjectMapper();
			String json="{}";
			try {
				json = mapper.writeValueAsString(record);
			} catch (JsonProcessingException e) {
				logger.error("json解析失败"+e.getMessage(),e);
			}
			JSONObject item = JSONObject.parseObject(json);
			for (Field field : oConvertUtils.getAllFields(record)) {
				if (field.getAnnotation(Dict.class) != null) {
					String code = field.getAnnotation(Dict.class).dicCode();
					String text = field.getAnnotation(Dict.class).dicText();
					String table = field.getAnnotation(Dict.class).dictTable();
					String key = String.valueOf(item.get(field.getName()));

					//翻译字典值对应的txt
					if(StringUtils.isNotBlank(table)){
						String textValue = translateDictValue(code, text, table, key);
						item.put(field.getName() + DictConstants.DICT_TEXT_SUFFIX, textValue);
					}else{
						if(!(oConvertUtils.isEmpty(key))) {
                            Map<String, String> map = queryDictModelByKey(code, key);
                            item.put(field.getName() + DictConstants.DICT_TEXT_SUFFIX, map.get("text"));
                            item.put(field.getName() + DictConstants.DICT_THEME_SUFFIX, map.get("theme"));
						}
					}
				}
				//date类型默认转换string格式化日期
				if (field.getType().getName().equals("java.util.Date")&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
					SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
				}
			}
			items.add(item);
		}
		return items;
	}





	/**
	 *  翻译字典文本
	 * @param code
	 * @param text
	 * @param table
	 * @param key
	 * @return
	 */
	public String translateDictValue(String code, String text, String table, String key) {
		if(oConvertUtils.isEmpty(key)) {
			return null;
		}
		StringBuffer textValue=new StringBuffer();
		String[] keys = key.split(",");
		for (String k : keys) {
			String tmpValue = null;
			if (k.trim().length() == 0) {
				continue; //跳过循环
			}
			if (!StringUtils.isEmpty(table)){
				tmpValue = dictDataService.translateDictFromTable(table,text,code,k.trim());
			}else {
				tmpValue = dictDataService.selectDictLabel(code, k.trim());
			}
			if (tmpValue != null) {
				if (!"".equals(textValue.toString())) {
					textValue.append(",");
				}
				textValue.append(tmpValue);
			}

		}
		return textValue.toString();
	}

	public Map<String, String> queryDictModelByKey(String code, String key) {
		if(oConvertUtils.isEmpty(key)) {
			return null;
		}
		Map<String, String> map = new HashMap<>();
		StringBuffer textValue = new StringBuffer();
		StringBuffer themeValue = new StringBuffer();
		String[] keys = key.split(",");
		for (String k : keys) {
			if (k.trim().length() == 0) {
				continue; //跳过循环
			}
			DictModel model = dictDataService.queryDictModelByKey(code, k.trim());
			if (model != null) {
				if (!"".equals(textValue.toString())) {
					textValue.append(",");
					themeValue.append(",");
				}
				textValue.append(model.getText());
				themeValue.append(StringUtils.isNotBlank(model.getTheme()) ? model.getTheme() : "primary");
			}
		}
		map.put("text", textValue.toString());
		map.put("theme", themeValue.toString());
		return map;
	}



}